/**
 * 
 */
package pl.koziolweb.wfm.server;

import java.io.FileFilter;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import pl.koziolweb.wfm.client.components.File;
import pl.koziolweb.wfm.client.components.TreeService;
import pl.koziolweb.wfm.server.util.ConfigurationLoadaer;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * @author bartlomiejk
 * 
 */
public class TreeServiceImpl extends RemoteServiceServlet implements
		TreeService {

	private static final long serialVersionUID = 1L;

	private final File ROOT;

	private final java.io.File SYSTEM_ROOT;

	public TreeServiceImpl() {
		super();
		ROOT = new File("", "/", 0l, (File) null, true);
		ConfigurationLoadaer cl = ConfigurationLoadaer.getINSTANCE();
		SYSTEM_ROOT = new java.io.File(cl.getProperty("system.root"));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * pl.koziolweb.wfm.client.components.TreeService#fileList(pl.koziolweb.
	 * wfm.client.components.File)
	 */
	@Override
	public File[] fileList(File parent) {
		java.io.File realFile = new java.io.File(SYSTEM_ROOT + "/"
				+ parent.getPath() + "/" + parent.getName());
		if (realFile.isDirectory()) {
			List<File> files = new LinkedList<File>();
			for (java.io.File real : realFile.listFiles(new WFMFileFilter())) {
				if (real.isHidden()) {
					continue;
				}
				File file = new File();
				file.setDirectory(real.isDirectory());
				file.setName(real.getName());
				file.setParent(parent);
				file.setPath(parent.getPath() + "/" + parent.getName());
				file.setSize(real.length());
				files.add(file);
			}

			Collections.sort(files);
			if (files.size() > 0) {
				return files.toArray(new File[files.size() - 1]);
			}
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * pl.koziolweb.wfm.client.components.TreeService#getFileContent(pl.koziolweb
	 * .wfm.client.components.File)
	 */
	@Override
	public String getFileContent(File file) {
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.koziolweb.wfm.client.components.TreeService#getRoot()
	 */
	@Override
	public File getRoot() {
		return ROOT;
	}

	private static class WFMFileFilter implements FileFilter {

		@Override
		public boolean accept(java.io.File pathname) {
			if (pathname.isDirectory()) {
				return true;
			}
			String[] exts = ConfigurationLoadaer.getINSTANCE().getProperty(
					"correct.files.extensions").split(",");
			for (String ext : exts) {
				if (pathname.getName().endsWith(ext.trim())) {
					return true;
				}
			}
			return false;
		}
	}
}
